package com.hxzy.common.controller;

import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.ServletUtils;
import com.hxzy.common.vo.PageVO;
import com.hxzy.common.vo.R;
import com.hxzy.entity.Employee;
import com.hxzy.mapper.ExistsMapper;
import com.hxzy.service.ExistsService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 通用控制器(以前的servlet技术)
 * @author Administrator
 */
public class BaseController {

    @Autowired
    protected ExistsService  existsService;

    private static final String PAGE_NUM_NAME="page";

    private static final String PAGE_SIZE_NAME="size";

    /**
     * 启动pageHelper分页 PageHelper.startPage(1, 10);
     */
    protected void startPageHelper(){
        //当前第几页
        int page= ServletUtils.getParamsToInt(PAGE_NUM_NAME);
        //每页多少笔
        int size=ServletUtils.getParamsToInt(PAGE_SIZE_NAME);

        //使用pagehelper，开启mybatis分页拦截器
        PageHelper.startPage(page,size);
    }

    /**
     * 把pageHelper返回的Page对象转换成自已定义的对象
     * @param list
     * @return
     */
    protected R  pageToPageVO(List list){
        PageVO  pageVO=new PageVO();

        //mybatis分页插件
       if(list instanceof Page){
           Page  pg= (Page) list;
           pageVO.setTotal(pg.getTotal());
           pageVO.setRows(pg.getResult());
       }else{
           //普通的list
           pageVO.setRows(list);
           pageVO.setTotal(0L);
       }
       return  R.okHasData(pageVO);
    }

    public R toR(int value){
        return value>0? R.build(AckCode.SUCCESS): R.build(AckCode.DATABASE_ERROR);
    }

    public R toR(boolean value){
        return value? R.build(AckCode.SUCCESS): R.build(AckCode.DATABASE_ERROR);
    }


    /**
     * 导出集合数据到excel表中
     * @param response
     * @param cls
     * @param arrList
     * @param <T>
     * @throws IOException
     */
    public <T> void writeListToExcel(HttpServletResponse response,Class<T> cls,List<T> arrList) throws IOException {
        //设定输出到浏览器的格式   .xlsx 对应的 mime-type类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        // 文件名
        String fileName = System.currentTimeMillis() + ".xlsx";
        //设定给浏览器，告诉响应给浏览器文件名
        response.setHeader("Content-disposition", "attachment;filename="+fileName);

        EasyExcel.write(response.getOutputStream(), cls).sheet("内容").doWrite(arrList);
    }
}
